# 方法一 暴力解法
class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        n = len(nums)
        ans = []
        for i in range(n - 3):
            for j in range(i + 1, n - 2):
                for z in range(j + 1, n - 1):
                    for k in range(z + 1, n):
                        ret = []
                        total = nums[i] + nums[j] + nums[z] + nums[k]
                        if total == target:
                            ret = [nums[i], nums[j], nums[z], nums[k]]
                            ret.sort()
                            ans.append(ret)
        # 去重
        uique_ans = []
        senn = set()
        for x in ans:
            tuple_x = tuple(x)
            if tuple_x not in senn:
                senn.add(tuple_x)
                uique_ans.append(x)
        return uique_ans
# 方法二 排序+双指针
class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        nums.sort()
        ans = []
        n = len(nums)
        for a in range(n - 3):# 枚举第一个数
            x = nums[a]
            if a and x == nums[a - 1]:# 跳过重复数字
                continue
            if nums[a] + nums[a + 1]+ nums[a + 2] + nums[a + 3] > target:
                break
            if x + nums[n - 1] + nums[n - 2] + nums[n - 3] < target:
                continue
            for b in range(a + 1, n - 2): # 枚举第二个数
                y = nums[b]
                if b > a + 1 and nums[b] == nums[b - 1]:
                    continue
                if x + y + nums[b + 1] + nums[b + 2] > target:
                    break
                if x + y + nums[n - 1] + nums[n - 2] < target:
                    continue
                c = b + 1
                d = n - 1
                while c < d:
                    s = x + y + nums[c] + nums[d]
                    if s > target:
                        d -= 1
                    elif s < target:
                        c += 1
                    else:
                        ans.append([x, y, nums[c], nums[d]])
                        c += 1
                        while c < d and nums[c] == nums[c - 1]:
                            c += 1
                        d -= 1
                        while c < d and nums[d] == nums[d + 1]:
                            d -= 1
        return ans